package com.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.Objects;

/**
 * 轮询算法(5次)
 */
public class LeeRoundRobinRule extends AbstractLoadBalancerRule {

    // 当前服务执行次数
    private int total = 0;
    // 当前服务下标
    private int index = 0;

    @Override
    public Server choose(Object o) {
        ILoadBalancer loadBalancer = super.getLoadBalancer();
        if (Objects.isNull(loadBalancer)) {
            return null;
        }

        Server server = null;
        while (server == null) {
            if (Thread.interrupted()) {
                return null;
            }
            // 获取全部服务
            List<Server> allServers = loadBalancer.getAllServers();
            server = total++%5 == 0 ? allServers.get(index = ++index == allServers.size() ? 0 : index) : allServers.get(index);
        }
        return server;
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }
}
